<template>
  <el-card class="role-card">
    <div class="home-box">
      <el-form :inline="true" :model="searchForm" v-show="showSearch">
        <el-form-item label="工号">
          <el-input v-model="searchForm.num" placeholder="工号" />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="getUserListByNum"
            style="margin-left: -16px"
          >
            按工号查询
          </el-button>
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="姓名" />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="getUserListByName"
            style="margin-left: -16px"
          >
            按姓名查询
          </el-button>
        </el-form-item>

        <el-form-item label="按部门查询">
          <el-tree-select
            v-model="deptId"
            style="width: 100%"
            :data="deptData"
            node-key="id"
            check-strictly
            :props="defaultProps"
            @change="getUserListByDeptId"
          >
            <template #default="{ data }">
              <span class="menu">
                <span style="margin-right: 10px">{{ data.deptName }}</span>
                <el-tag :type="levelType(data.level)" size="small">
                  {{ levelTest(data.level) }}
                </el-tag>
              </span>
            </template>
          </el-tree-select>
        </el-form-item>

        <!-- <el-form-item>
          <el-button
            type="primary"
            @click="getUserListByDeptId"
            v-auth="'查询员工'"
            style="margin-left: -16px"
          >
            按部门查询
          </el-button>
        </el-form-item> -->

        <!-- <el-form-item>
          <el-button
            @click="resetGetUserListA"
            type="primary"
            v-auth="'重置查询员工'"
          >
            重置
          </el-button>
        </el-form-item> -->
      </el-form>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="resetUserList"
        @onImportClick="handleImport"
        @onOutClick="onDownTemplate"
        @onAddClick="onDownTemplate"
      >
        <template #left-btn>
          <el-row :gutter="10">
            <el-col :span="1.5" v-auth="'新增员工'">
              <addUser @getUserList="resetUserList" />
            </el-col>

            <el-col :span="1.5" v-auth="'修改员工'">
              <updateUser @getUserList="resetUserList" :selection="selection" />
            </el-col>

            <!-- <el-col :span="1.5" v-auth="'删除员工'">
              <deleteUser @getUserList="resetUserList" :selection="selection" />
            </el-col> -->
            <el-col :span="1.5" v-auth="'启用员工'">
              <el-button
                type="default"
                plain
                icon="check"
                :disabled="selection.length === 0"
                @click="handleState(1)"
              >
                启用
              </el-button>
            </el-col>

            <el-col :span="1.5" v-auth="'停用员工'">
              <el-button
                type="danger"
                plain
                icon="delete"
                :disabled="selection.length === 0"
                @click="handleState(0)"
              >
                停用
              </el-button>
            </el-col>

            <el-col :span="1.5" v-auth="'导入员工'">
              <el-button type="info" plain icon="Upload" @click="handleImport">
                导入
              </el-button>
            </el-col>

            <!-- <el-col :span="1.5">
              <showInfo :emp-name="empName" />
            </el-col> -->
            <el-col :span="1.5" v-auth="'导出员工'">
              <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleOut"
              >
                导出
              </el-button>
            </el-col>
          </el-row>
        </template>
      </right-toolbar>

      <el-table
        :data="limit()"
        v-loading="loading"
        ref="tableRef"
        element-loading-text="加载中..."
        :row-key="(row) => row.id"
        border
        @selection-change="selectChange"
      >
        <el-table-column type="selection" align="center" />

        <el-table-column prop="num" label="工号" align="center" />

        <el-table-column prop="name" label="姓名" width="150" align="center" />
        <el-table-column
          prop="phoneNum1"
          label="联系电话1"
          width="150"
          align="center"
        />

        <el-table-column
          prop="phoneNum2"
          label="联系电话2"
          width="150"
          align="center"
        />

        <el-table-column prop="email" label="邮箱" width="150" align="center" />

        <el-table-column
          prop="idNum"
          label="身份证号"
          width="150"
          align="center"
        />

        <el-table-column
          prop="birthday"
          label="出生年月"
          width="150"
          align="center"
        />

        <el-table-column
          label="通信地址"
          prop="address"
          width="180"
          align="center"
        />

        <el-table-column label="部门" width="300" align="center">
          <template #default="{ row }">
            <el-text v-for="(item, index) in row.deptNames" :key="index">
              {{ item }}
              <br />
            </el-text>
          </template>
        </el-table-column>

        <el-table-column label="岗位" width="180" align="center">
          <template #default="{ row }">
            <el-text v-for="(item, index) in row.postName" :key="index">
              {{ item }}
              <br />
            </el-text>
          </template>
        </el-table-column>

        <el-table-column
          prop="regionName"
          label="地域"
          width="180"
          align="center"
        />

        <el-table-column
          prop="roleName"
          label="职务"
          width="180"
          align="center"
        />

        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.state == '0' ? 'danger' : 'success'">
              {{ row.state == "0" ? "停用" : "正常" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="120"
          align="center"
          v-auth="'重置密码'"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="Lock"
              size="small"
              @click="resetPassword(row.id, row.num, row.name)"
            >
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页组件-->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        :pageSizes="[10, 20, 30, 40]"
        @pagination="limit()"
      />

      <!-- 用户导入对话框 -->
      <UploadExcel
        v-model="upload.open"
        :title="upload.upLoadTitle"
        :url="importUrl"
        @onSuccess="onSuccess"
        @onDownTemplate="onDownTemplate"
      ></UploadExcel>
    </div>
  </el-card>
</template>
<script>
export default {
  name: "adminList",
};
</script>
<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElNotification } from "element-plus";
import {
  changeState,
  getEmpsByDeptId,
  getEmpsByNumOrName,
  resetPwd
} from "@/service/api/user";
import { getDeptTree } from "@/service/api/dept";
import eventBus from "@/utils/event-bus";
import addUser from "./components/addUser.vue";
import updateUser from "./components/updateUser.vue";
import deleteUser from "./components/deleteUser.vue";
import UploadExcel from "@/components/UploadExcel/index.vue";
import showInfo from "./components/showInfo.vue";
import { TEST_URL, TOKEN } from "@/constant";
import { getEmployeeTemplate } from "@/api/template";
import store from "@/store";
import { getItem } from "@/utils/storage";

const deptData = ref([]);
const router = useRouter();
const showSearch = ref(true);
const tableRef = ref();
const tableData = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const selection = ref([]);
const importUrl = ref("/auth/excel/employee/upload");
const defaultProps = {
  label: "deptName",
};
const searchForm = ref({
  num: null,
  name: null,
});

/**
 * 将数据转换为表格数据和分页数据
 */
const transTableData = async (data) => {
  total.value = data.length;
  tableData.value = data;
};

const deptId = ref(null);
/**
 * 根据部门id获取员工列表
 */
const getUserListByDeptId = async () => {
  // loading.value = true;
  searchForm.value.name = null;
  searchForm.value.num = null;
  const data = (await getEmpsByDeptId(deptId.value)) || [];
  transTableData(data);
  // loading.value = false;
};

/**
 * 根据工号或姓名获取员工列表
 */
const getUserListByNumOrName = async () => {
  // loading.value = true;
  const data = (await getEmpsByNumOrName(searchForm.value)) || [];
  transTableData(data);
  // loading.value = false;
};

const getUserListByNum = () => {
  searchForm.value.name = null;
  deptId.value = null;
  getUserListByNumOrName();
};

const getUserListByName = () => {
  searchForm.value.num = null;
  deptId.value = null;
  getUserListByNumOrName();
};

//前端限制分页（tableData为当前展示页表格）
const limit = () => {
  return tableData.value.filter(
    (item, index) =>
      index < pageNum.value * pageSize.value &&
      index >= pageSize.value * (pageNum.value - 1)
  );
};

const handleState = async (stateId) => {
  const data = selection.value.map((item) => {
    return {
      empId: item.id,
      stateId,
    };
  });

  let msg = "启用员工成功";

  if (stateId === 0) {
    msg = "停用员工成功";
  }

  const res = await changeState(data);
  if (res.code === 200) {
    ElMessage.success(msg);
    resetUserList();
  }
};

/**
 * 获取账号列表--重置查询条件
 */
const resetUserList = async () => {
  deptId.value = null;
  searchForm.value = {
    num: null,
    name: null,
  };
  getUserListByNumOrName();
};

/**
 * 勾选表格CheckBox的回调函数-获取勾选的数组
 */
const selectChange = (select) => {
  selection.value = select;
};

/*** 用户导入参数 */
const upload = ref({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  upLoadTitle: "员工导入",
});

/** 导入按钮操作 */
function handleImport() {
  upload.value.open = true;
}

/** 文件上传成功处理 */
const onSuccess = (res) => {
  if (typeof res === "string" && res.length > 0) {
    store.commit("userManagement/setErrorList", res);
    router.push({
      path: "/emp/error",
    });
    // console.log(store.state.userManagement.errorList);

    // res = res.replace(/\n\n/g, "<br>");
    // ElNotification({
    //   title: "有员工信息添加失败,请查看错误日志",
    //   dangerouslyUseHTMLString: true,
    //   duration: 0,
    //   message: res,
    //   type: "error",
    // });
  } else {
    ElMessage.success("导入用户成功");
    resetUserList();
  }
  upload.value.open = false;
};
const onDownTemplate = () => {
  getEmployeeTemplate().then((data) => {
    ElMessage.success("模版下载成功");
  });
};

/** 导出按钮操作 */
function handleOut() {
  const deptIdParam = deptId.value === null ? "" : `?deptId=${deptId.value}`;

  const numParam =
    searchForm.value.num === null ? "" : `?num=${searchForm.value.num}`;

  const nameParam =
    searchForm.value.name === null ? "" : `?name=${searchForm.value.name}`;

  const token = getItem(TOKEN);

  const tokenParam = token ? `?token=Bearer ${token}` : "?token=";

  window.open(
    `${TEST_URL}/auth/excel/employee/download/` +
      deptIdParam +
      nameParam +
      numParam +
      tokenParam
  );
}

const exportToExcel = () => {
  // // 将数据转换为工作簿对象
  // const ws = XLSX.utils.json_to_sheet(tableData.value);
  // // 创建一个新的工作簿并添加工作表
  // const wb = XLSX.utils.book_new();
  // XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  // // 将工作簿转换为blob对象，以便可以下载
  // const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
  // // 使用FileSaver保存文件
  // try {
  //   saveAs(
  //     new Blob([wbout], { type: "application/octet-stream" }),
  //     "data.xlsx"
  //   );
  // } catch (e) {
  //   if (typeof console !== "undefined") console.log(e, wbout);
  // }
  // return wbout;
};

const levelType = (level) => {
  if (level === 1) return "";
  else if (level === 2) return "success";
  else if (level === 3) return "warning";
  else return "danger";
};

const levelTest = (level) => {
  if (level === 1) return "一级";
  else if (level === 2) return "二级";
  else if (level === 3) return "三级";
  else return "四级";
};

const resetPassword = async (id, num, name) => {
  await resetPwd(id, "123456", 0);
  ElNotification({
    title: "重置密码成功",
    dangerouslyUseHTMLString: true,
    message: `工号：${num}<br>姓名：${name}<br>默认密码：123456`,
    type: "success",
  });
};

onMounted(async () => {
  deptData.value = await getDeptTree();
  resetUserList();
});
</script>

<style lang="scss" scoped>
.home-box {
  .header {
    margin-bottom: 22px;
    text-align: right;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
  .el-timeline-item {
    padding-bottom: 1px;
  }
  .cell {
    display: inline-block;
  }
}
.el-card {
  border-radius: 10px;
}
</style>
